# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document

class MaxKeySSOSettings(Document):
    def validate(self):
        """验证设置"""
        # 确保必填字段已填写
        if self.enabled:
            if not self.client_id:
                frappe.throw("必须提供 Client ID")
            if not self.client_secret:
                frappe.throw("必须提供 Client Secret")
            if not self.base_url:
                frappe.throw("必须提供 MaxKey 基础 URL")
                
        # 确保 URL 无尾随斜杠
        if self.base_url and self.base_url.endswith('/'):
            self.base_url = self.base_url.rstrip('/')
        
        # 确保端点以斜杠开头
        if self.authz_endpoint and not self.authz_endpoint.startswith('/'):
            self.authz_endpoint = '/' + self.authz_endpoint
            
        if self.token_endpoint and not self.token_endpoint.startswith('/'):
            self.token_endpoint = '/' + self.token_endpoint
            
        if self.userinfo_endpoint and not self.userinfo_endpoint.startswith('/'):
            self.userinfo_endpoint = '/' + self.userinfo_endpoint
            
    def get_auth_url(self):
        """获取完整的授权 URL"""
        return self.base_url + self.authz_endpoint
        
    def get_token_url(self):
        """获取完整的 Token URL"""
        return self.base_url + self.token_endpoint
        
    def get_userinfo_url(self):
        """获取完整的用户信息 URL"""
        return self.base_url + self.userinfo_endpoint
